package study.多线程;

public class Thread_demo {
	
	public static Object lock = new Object();
	public static Integer i = 0;
	public static Integer num = 10;
	
	public static void main(String[] args) throws InterruptedException {
	
		ThredOne thredOne = new ThredOne();
		ThredTwo thredTwo = new ThredTwo();
		
		thredOne.setName("锁一");
		thredTwo.setName("锁二");
		
		
		thredOne.start();
		thredTwo.start();
		
		
	
	
	
	
	}
}

class ThredOne extends Thread{
	@Override
	public void run() {
		while(true){
			synchronized (Thread_demo.lock){
				if(Thread_demo.num == 0){
					break;
				}else {
					if(Thread_demo.i == 0){
						try {
							// wait()方法会进行等待并释放锁。
							// 这样two就可以获取锁，然而当i == 0的时候two必然会更改 i 并且启动线程。
							Thread_demo.lock.wait();
						} catch (InterruptedException e) {
							throw new RuntimeException(e);
						}
					}else{
						System.out.println("第一个锁");
						Thread_demo.lock.notifyAll();
						Thread_demo.i = 0;
						Thread_demo.num --;
					}
				}
			}
		}
	}
}

class ThredTwo extends Thread{
	@Override
	public void run() {
		while(true){
			synchronized (Thread_demo.lock){
				if(Thread_demo.num == 0){
					break;
				}else {
					if(Thread_demo.i == 1){
						try {
							Thread_demo.lock.wait();
						} catch (InterruptedException e) {
							throw new RuntimeException(e);
						}
					}else{
						System.out.println("第二个锁");
						Thread_demo.lock.notifyAll();
						Thread_demo.i = 1;
						Thread_demo.num --;
					}
				}
			}
		}
	}
}
